<template>
	<view class="order-list-container">
		<!-- 加载中蒙版 -->
		<qmy-mask-load :dataLoaded="dataLoaded"></qmy-mask-load>

		<!-- 顶部导航栏 -->
		<qmy-custom-navbar title="我的订单"></qmy-custom-navbar>

		<!-- 固定头部区域 -->
		<view class="fixed-header" :style="{top: menuObject.top + menuObject.height + 'px'}">
			<!-- 搜索栏 -->
			<view class="search-bar">
				<view class="search-input-box">
					<text class="iconfont ic-sousuo col-00ba31 fs-40 mr-10"></text>
					<input type="text" v-model="searchKeyword" placeholder="搜索订单号/商品名称" @confirm="handleSearch"
						placeholder-class="search-placeholder" />
					<text class="col-0a2e36 fs-40 iconfont ic-qingchu ml-10" v-if="searchKeyword"
						@click="clearSearch"></text>
				</view>
			</view>

			<v-tabs ref="tabs" field="name" :zIndex="1" :scroll="true" bgColor="#ffffff00" pillsColor="#ffffff00"
				fontSize="28rpx" pillsStyle="box" activeFontSize="30rpx" lineHeight="4rpx" :lineScale="0.2"
				activeColor="linear-gradient(to right, #14cc60, #14cc60)" paddingItem="0rpx 40rpx"
				color="linear-gradient(to right, #616161, #616161)" lineColor="#14cc60" v-model="currentTab"
				:tabs="tabs" @change="handleTabChange"></v-tabs>
		</view>

		<!-- 订单列表 -->
		<scroll-view scroll-y class="order-list"
			:style="{top: menuObject.top + menuObject.height + 'px',paddingTop:'200rpx'}" @scrolltolower="loadMore"
			:refresher-enabled="true" :refresher-triggered="isRefreshing" @refresherrefresh="onRefresh">
			<!-- 空状态 -->
			<view v-if="orderList.length === 0" class="empty-box">
				<image src="https://gd-hbimg.huaban.com/e201e80eaa01c7da009f2d71eda014d68ba3bf78168c-Hh3zd2"
					mode="aspectFit"></image>
				<text>暂无相关订单</text>
			</view>

			<!-- 订单列表内容 -->
			<view class="order-item" v-for="order in orderList" :key="order._id">
				<view class="order-header">
					<view class="order-number">
						<text @click="$copy(order.out_trade_no)">订单号：{{order.out_trade_no}}
						</text>
						<text class="order-status"
							:class="'status-' + order.status">{{getStatusText(order.status)}}</text>
					</view>
				</view>

				<view class="order-content" @click="goOrderDetail(order._id)">
					<view class="goods-list">
						<view class="goods-images">
							<image v-for="(goods, index) in order.custom.goods_list.slice(0, 3)" :key="index"
								:src="goods.image" mode="aspectFill"></image>
							<view class="goods-info-box" v-if="order.custom.goods_list.length == 1">
								<view class="goods-name text-element-2">
									{{order.custom.goods_list[0].name}}
								</view>
								<scroll-view scroll-x class="goods-service"
									v-if="order.custom.goods_list[0].goods_snapshot && order.custom.goods_list[0].goods_snapshot.services.length">
									<view class="service-tags-container">
										<text class="service-tag"
											v-for="(tag, idx) in order.custom.goods_list[0].goods_snapshot.services"
											:key="idx">{{tag}}</text>
									</view>
								</scroll-view>
							</view>
						</view>
						<view class="order-info">
							<view class="total-amount">
								<text class="amount">¥{{(order.total_fee/100).toFixed(2)}}</text>
							</view>
							<text class="goods-count">共{{getTotalQuantity(order.custom.goods_list)}}件商品</text>
						</view>
					</view>
				</view>

				<view class="order-footer">
					<!-- 已关闭状态 -->
					<template v-if="order.status === -1">
						<view class="btn btn-plain" @click="deleteOrder(order)">删除订单</view>
					</template>
					<!-- 待付款状态 -->
					<template v-if="order.status === 0">
						<view class="btn btn-plain" @click="cancelOrder(order)">取消订单</view>
						<view class="btn btn-primary" @click="payOrder(order)">立即付款</view>
					</template>
					<!-- 待发货状态 -->
					<template v-if="order.status === 1">
						<view class="btn btn-plain" @click="applyRefund(order)">申请退款</view>
						<view class="btn btn-primary" @click="remindShip(order)">提醒发货</view>
					</template>
					<!-- 待收货状态 -->
					<template v-if="order.status === 5">
						<view class="btn btn-plain" @click="getExpressInfo(order)">查看物流</view>
						<view class="btn btn-primary" @click="confirmReceive(order)">确认收货</view>
					</template>
					<!-- 待评价状态 -->
					<template v-if="order.status === 6">
						<view class="btn btn-primary" @click="goEvaluate(order)">评价晒单</view>
					</template>
					<!-- 退款中状态 -->
					<template v-if="order.status === 4">
						<view class="btn btn-plain" @click="viewRefundDetail(order)">退款详情</view>
						<view class="btn btn-primary" @click="cancelRefund(order)">取消退款</view>
					</template>
				</view>
			</view>
			<qmy-logo :loading="load" v-if="orderList.length"></qmy-logo>
		</scroll-view>

		<!-- 取消订单确认弹窗 -->
		<uni-popup ref="cancelPopup" type="dialog">
			<uni-popup-dialog type="warning" title="取消订单" content="确定要取消该订单吗？" :before-close="true"
				@confirm="confirmCancelOrder" @close="cancelCancelOrder">
			</uni-popup-dialog>
		</uni-popup>

		<!-- 确认收货确认弹窗 -->
		<uni-popup ref="receivePopup" type="dialog">
			<uni-popup-dialog type="warning" title="确认收货" content="确认已收到商品吗？" :before-close="true"
				@confirm="confirmReceiveOrder" @close="cancelReceiveOrder">
			</uni-popup-dialog>
		</uni-popup>

		<!-- 删除订单确认弹窗 -->
		<uni-popup ref="deletePopup" type="dialog">
			<uni-popup-dialog type="warning" title="删除订单" content="确定要删除该订单吗？" :before-close="true"
				@confirm="confirmDeleteOrder" @close="cancelDeleteOrder">
			</uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	// const plugin = requirePlugin("logisticsPlugin")
	export default {
		data() {
			return {
				// #ifdef MP-WEIXIN
				menuObject: uni.getMenuButtonBoundingClientRect(),
				// #endif
				// #ifndef MP-WEIXIN
				menuObject: 0,
				// #endif
				tabs: [{
					name: '全部',
					value: -1
				}, {
					name: '待付款',
					value: 0
				}, {
					name: '待发货',
					value: 1
				}, {
					name: '待收货',
					value: 5
				}, {
					name: '待评价',
					value: 6
				}, {
					name: '退款/售后',
					value: 4
				}],
				currentTab: 0,
				searchKeyword: '',
				orderList: [],
				page: 1,
				pageSize: 10,
				isRefreshing: false,
				hasMore: true,
				dataLoaded: false,
				currentOrder: null, // 当前操作的订单
				load: false, // 是否加载中
			}
		},
		onLoad(options) {
			// 设置初始标签页
			if (options.status) {
				const index = this.tabs.findIndex(tab => tab.value === parseInt(options.status));
				if (index !== -1) {
					this.currentTab = index;
				}
			}
			this.loadOrderList();
		},
		onPullDownRefresh() {
			this.onRefresh();
		},
		methods: {
			// 加载订单列表
			async loadOrderList(type = 'refresh') {
				this.load = true;
				this.$Route('get-private-data', !this.dataLoaded).getOrderList({
					status: this.tabs[this.currentTab].value,
					keyword: this.searchKeyword,
					page: this.page,
					pageSize: this.pageSize
				}).then(res => {
					if (type === 'refresh') {
						this.orderList = res.data;
					} else {
						this.orderList = [...this.orderList, ...res.data];
					}
					this.hasMore = res.data.length === this.pageSize;
				}).catch(err => {
					console.error('遇到错误:', err); // 打印错误信息
					let {
						code,
						msg
					} = this.$parseError(err); // 调用公共解析方法
					this.$Toast(msg);
					setTimeout(() => {
						if (code === 401) {
							this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
						}
					}, 1000);
				}).finally(() => {
					this.load = false;
					this.dataLoaded = true;
					this.isRefreshing = false;
					uni.stopPullDownRefresh();
				});

			},

			// 处理标签页切换
			handleTabChange(index) {
				this.currentTab = index;
				this.page = 1;
				this.hasMore = true;
				this.loadOrderList('refresh');
			},

			// 处理搜索
			handleSearch() {
				this.page = 1;
				this.hasMore = true;
				this.loadOrderList('refresh');
			},

			// 清除搜索
			clearSearch() {
				this.searchKeyword = '';
				this.handleSearch();
			},

			// 加载更多
			loadMore() {
				if (this.hasMore) {
					this.page++;
					this.loadOrderList('more');
				} else {
					return this.$Toast('没有更多数据了');
				}
			},

			// 下拉刷新
			onRefresh() {
				this.isRefreshing = true;
				this.page = 1;
				this.hasMore = true;
				this.loadOrderList('refresh');
			},

			// 获取状态文本
			getStatusText(status) {
				const statusMap = {
					'-1': '已关闭',
					'0': '待付款',
					'1': '待发货',
					'2': '已部分退款',
					'3': '已全额退款',
					'4': '退款中',
					'5': '待收货',
					'6': '待评价',
					'7': '已完成'
				};
				return statusMap[status] || '未知状态';
			},

			// 格式化日期
			formatDate(timestamp) {
				const date = new Date(timestamp);
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
			},

			// 跳转订单详情
			goOrderDetail(orderId) {
				uni.navigateTo({
					url: `/qmy_user/user/order/detail?id=${orderId}`,
					events: {
						refreshData: (data) => {
							this.loadOrderList('refresh');
						}
					}
				});
			},

			// 取消订单
			cancelOrder(order) {
				this.currentOrder = order;
				this.$refs.cancelPopup.open();
			},

			// 确认取消订单
			async confirmCancelOrder() {
				if (!this.currentOrder) return;
				this.$Route('update-private-data').cancelOrder(this.currentOrder._id).then((res) => {
					this.$Toast(res.msg);
					setTimeout(() => {
						this.loadOrderList('refresh');
					}, 1000);
				}).catch(err => {
					console.error('遇到错误:', err); // 打印错误信息
					let {
						code,
						msg
					} = this.$parseError(err); // 调用公共解析方法
					this.$Toast(msg);
					setTimeout(() => {
						if (code === 401) {
							this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
						}
					}, 1000);
				}).finally(() => {
					this.currentOrder = null;
					this.$refs.cancelPopup.close();
				});
			},

			// 取消取消订单
			cancelCancelOrder() {
				this.currentOrder = null;
				this.$refs.cancelPopup.close();
			},

			// 获取物流信息
			async getExpressInfo(order) {
				this.$Route('get-private-data').getExpressInfo(order._id).then(res => {
					// plugin.openWaybillTracking({
					// 	waybillToken: res.data.waybill_token
					// });
				}).catch(err => {
					console.error('遇到错误:', err);
					let {
						code,
						msg
					} = this.$parseError(err);
					this.$Toast(msg);
					setTimeout(() => {
						if (code === 401) {
							this.$NavigateTo('/qmy_user/login');
						}
					}, 1000);
				});
			},

			// 支付订单
			async payOrder(order) {
				// 节流
				this.$debounce(() => {
					let options = {
						order_no: order.order_no, // 业务系统订单号（即你自己业务系统的订单表的订单号）
						out_trade_no: order.out_trade_no, // 插件支付单号
						type: 'goods', // 订单类型
						description: `奇妙野商城订单-${order.out_trade_no}`, // 支付描述
						total_fee: order
							.total_fee, // 支付金额，单位分 100 = 1元（注意：因为是前端传的，此参数可能会被伪造，回调时需要再校验下是否和自己业务订单金额一致）
					};
					let optionsStr = encodeURI(JSON.stringify(options));
					uni.navigateTo({
						url: `/pages/detail/pay-desk?options=${optionsStr}`,
						events: {
							refreshData: (data) => {
								this.loadOrderList('refresh');
							}
						}
					});
				}, 1000, true, "payOrder")

			},

			// 申请退款
			applyRefund(order) {
				uni.navigateTo({
					url: `/qmy_user/user/order/refund?id=${order._id}`,
					events: {
						refreshData: (data) => {
							this.loadOrderList('refresh');
						}
					}
				});
			},

			// 取消退款
			cancelRefund(order) {
				// 节流
				this.$debounce(() => {
					this.$Route('update-private-data').cancelRefund(order._id).then(res => {
						this.$Toast(res.msg);
						setTimeout(() => {
							this.loadOrderList('refresh');
						}, 1000);
					}).catch(err => {
						console.error('遇到错误:', err); // 打印错误信息
						let {
							code,
							msg
						} = this.$parseError(err); // 调用公共解析方法
						setTimeout(() => {
							if (code === 401) {
								this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
							}
						}, 1000);
						this.$Toast(msg);
					});
				}, 1000, true, "cancelRefund");
			},

			// 提醒发货
			async remindShip(order) {
				this.$Route('update-private-data').remindShip(order._id).then(res => {
					this.$Toast(res.msg);
				}).catch(err => {
					console.error('遇到错误:', err);
					let {
						code,
						msg
					} = this.$parseError(err);
					this.$Toast(msg);
					setTimeout(() => {
						if (code === 401) {
							this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
						}
					}, 1000);
				});
			},

			// 查看物流
			viewLogistics(order) {
				this.$NavigateTo(`/qmy_user/user/order/logistics?id=${order._id}`);
			},

			// 确认收货
			confirmReceive(order) {
				this.currentOrder = order;
				this.$refs.receivePopup.open();
			},

			// 确认收货操作
			async confirmReceiveOrder() {
				if (!this.currentOrder) return;
				this.$Route('update-private-data').confirmReceive(this.currentOrder._id).then(res => {
					this.$Toast(res.msg);
					setTimeout(() => {
						this.loadOrderList('refresh');
					}, 1000);
				}).catch(err => {
					console.error('遇到错误:', err);
					let {
						code,
						msg
					} = this.$parseError(err);
					this.$Toast(msg);
					setTimeout(() => {
						if (code === 401) {
							this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
						}
					}, 1000);
				}).finally(() => {
					this.currentOrder = null;
					this.$refs.receivePopup.close();
				});

			},

			// 取消确认收货
			cancelReceiveOrder() {
				this.currentOrder = null;
				this.$refs.receivePopup.close();
			},

			// 删除订单
			deleteOrder(order) {
				this.currentOrder = order;
				this.$refs.deletePopup.open();
			},

			// 确认删除订单
			async confirmDeleteOrder() {
				if (!this.currentOrder) return;
				this.$Route('update-private-data').deleteOrder(this.currentOrder._id).then(res => {
					this.$Toast(res.msg);
					setTimeout(() => {
						this.loadOrderList('refresh');
					}, 1000);
				}).catch(err => {
					console.error('遇到错误:', err);
					let {
						code,
						msg
					} = this.$parseError(err);
					this.$Toast(msg);
				}).finally(() => {
					this.currentOrder = null;
					this.$refs.deletePopup.close();
				});
			},

			// 取消删除订单
			cancelDeleteOrder() {
				this.currentOrder = null;
				this.$refs.deletePopup.close();
			},

			// 去评价
			goEvaluate(order) {
				uni.navigateTo({
					url: `/qmy_user/user/order/evaluate?id=${order._id}`,
					events: {
						refreshData: (data) => {
							this.loadOrderList('refresh');
						}
					}
				})
			},

			// 查看退款详情
			viewRefundDetail(order) {
				this.$NavigateTo(`/qmy_user/user/order/refundDetail?id=${order._id}`);
			},

			// 计算商品总数量
			getTotalQuantity(goodsList) {
				return goodsList.reduce((total, goods) => total + (goods.quantity || 1), 0);
			},
		}
	}
</script>

<style lang="scss">
	.order-list-container {
		min-height: 100vh;
		background-color: #f7f7f7;
		position: relative;
	}

	.fixed-header {
		position: fixed;
		left: 0;
		right: 0;
		z-index: 1;
		background-color: #fff;
		height: 180rpx;
		overflow: hidden;
	}

	.search-bar {
		padding: 20rpx;
		background-color: #fff;
		border-bottom: 2rpx solid #f5f5f5;

		.search-input-box {
			display: flex;
			align-items: center;
			background-color: #f5f5f5;
			border-radius: 32rpx;
			padding: 0 24rpx;
			height: 64rpx;

			input {
				flex: 1;
				height: 100%;
				font-size: 26rpx;
			}

			.search-placeholder {
				color: #999;
			}
		}
	}

	.order-list {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		padding: 20rpx;
		box-sizing: border-box;
		padding-bottom: env(safe-area-inset-bottom);
	}

	.empty-box {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding-top: 200rpx;
		opacity: 0.5;

		image {
			width: 200rpx;
			height: 200rpx;
			margin-bottom: 20rpx;
		}

		text {
			font-size: 28rpx;
			color: #999;
		}
	}

	.order-item {
		background-color: #fff;
		border-radius: 20rpx;
		margin-bottom: 20rpx;
		overflow: hidden;

		.order-header {
			padding: 24rpx;
			border-bottom: 2rpx solid #f5f5f5;

			.order-number {
				display: flex;
				justify-content: space-between;
				align-items: center;
				font-size: 26rpx;
				color: #333;
				margin-bottom: 8rpx;

				.order-status {
					font-weight: 500;

					&.status-0 {
						color: #ff4f4f;
					}

					&.status-1 {
						color: #ffbc1e;
					}

					&.status-4 {
						color: #ff91ba;
					}

					&.status-5 {
						color: #14cc60;
					}

					&.status-6 {
						color: #5e9fff;
					}
				}
			}

			.order-time {
				font-size: 24rpx;
				color: #999;
			}
		}

		.order-content {
			padding: 24rpx;

			.goods-list {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.goods-images {
					display: flex;
					flex: 1;
					min-width: 0;

					image {
						width: 130rpx;
						height: 130rpx;
						border-radius: 12rpx;
						flex-shrink: 0;
						margin-right: 20rpx;
						background-color: #f5f5f5;
					}

					.goods-info-box {
						flex: 1;
						min-width: 0;
						padding-right: 20rpx;
						display: flex;
						flex-direction: column;
						justify-content: space-between;

						.goods-name {
							font-size: 28rpx;
							color: #333;
							line-height: 1.4;
							overflow: hidden;
							text-overflow: ellipsis;
							display: -webkit-box;
							-webkit-box-orient: vertical;
							-webkit-line-clamp: 2;
						}

						.goods-service {
							width: 100%;
							white-space: nowrap;

							.service-tags-container {
								display: inline-flex;
								padding: 4rpx 0;
							}

							.service-tag {
								display: inline-block;
								font-size: 22rpx;
								color: #14cc60;
								background-color: rgba(20, 204, 96, 0.1);
								padding: 4rpx 12rpx;
								border-radius: 4rpx;
								margin-right: 8rpx;
								flex-shrink: 0;

								&:last-child {
									margin-right: 0;
								}
							}
						}
					}
				}

				.order-info {
					flex-shrink: 0;
					text-align: right;
					margin-left: 20rpx;

					.total-amount {
						font-size: 26rpx;
						color: #666;
						margin-bottom: 8rpx;
						display: flex;
						flex-direction: row;
						white-space: nowrap;
						justify-content: flex-end;

						.amount {
							font-size: 32rpx;
							color: #ff4f4f;
							font-weight: bold;
							margin-left: 8rpx;
						}
					}

					.goods-count {
						font-size: 24rpx;
						color: #999;
					}
				}
			}
		}

		.order-footer {
			padding: 24rpx;
			border-top: 2rpx solid #f5f5f5;
			display: flex;
			justify-content: flex-end;
			align-items: center;

			.btn {
				padding: 12rpx 32rpx;
				border-radius: 32rpx;
				font-size: 26rpx;
				margin-left: 20rpx;

				&.btn-plain {
					border: 2rpx solid #ddd;
					color: #666;

					&:active {
						background-color: #f5f5f5;
					}
				}

				&.btn-primary {
					background-color: #14cc60;
					color: #fff;

					&:active {
						opacity: 0.8;
					}
				}
			}
		}
	}
</style>